/**
 * Created by chang on 2017/3/4.
 */

const fs = require('fs');
const resolve = require('resolve');
const yaml = require('js-yaml');
const _ = require('lodash');
const path = require('path');

const G_ENV = process.env.NODE_ENV || 'dev';
const BASEDIR = process.cwd();
const CONFIG_DIR = process.env.CONFIG_DIR || 'config';

function loadConfig(filename) {
    let filepath = null;
    try {
        filepath = resolve.sync(filename, {
            basedir: BASEDIR,
            extensions: ['.js', '.json', '.node', '.yaml', '.yml'],
            moduleDirectory: CONFIG_DIR
        });
    } catch (e) {
        return {};
    }

    if (/\.ya?ml$/.test(filepath)) {
        return _.assign({}, yaml.load(fs.readFileSync(filepath, 'utf8')));
    } else {
        return _.assign({}, require(filepath));
    }
}

module.exports = {
    get: (configName) => _.defaultsDeep(loadConfig(path.join(BASEDIR, CONFIG_DIR, G_ENV, configName)), loadConfig(configName)),
};



